import Vue from 'vue'
import {wsUrl} from './config'

Vue.prototype.$ws = new Vue({
	data() {
		return {
			ws: null,
		}
	},
	methods: {
		openWs() {
			this.ws = new WebSocket('ws://121.37.195.155:3005')

			this.ws.onopen = (err) => {
        console.log("onpen");
        // 开启用户登录请求监听
        this.$show.$on('userIsLoginSuccess', this.sendUserData)

      }
      this.ws.onerror = (err)=>{
        console.log('ws is err');
      }
			this.ws.onmessage = (msg) => {
        msg = JSON.parse(msg.data)
     
        switch (msg.type) {
          case 'usersendStaffNewMsg':
            // 发射成功事件
            this.$ws.$emit('usersendStaffNewMsg',msg.data)
            break;
        
          case 'userNewMsg':
            // 发射成功事件
            this.$ws.$emit('userNewMsg',msg.data)
            break;
        
          default:
            break;
        }
        
			}
		},
		send(type, data) {
			this.ws.send(
				JSON.stringify({
					type,
					data,
				})
			)
		},
		sendUserData(e) {
			// 将用户id发送给服务器
			this.send('save_user_socket', {
				uid: e,
			})
		},
	},
	created() {
		// 监听用户是否登录的事件   当用户登录成功时 给服务器发送事件
	
	},
})
